package com.angel.activity;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.graphics.Color;
import org.json.JSONException;
import org.json.JSONObject;


import com.angel.entity.ActivityDetailBean;
import com.angel.entity.FormFile;
import com.angel.entity.Task;
import com.angel.port.IActivity;
import com.angel.service.TaskService;
import com.angel.util.AsyncDownload;
import com.angel.util.AsyncDownload.CallBack;
import com.angel.util.BaseUtil;
import com.angel.util.ConstUtil;
import com.angel.util.HttpUtil;
import com.angel.util.NetUtil;
import com.angel.util.StringUtil;
import com.angel.util.UpLoadPicUtil;
import com.angel.util.UserInfoUtil;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

/** 活动详情 */
public class ActivityDetail extends Activity implements IActivity {
	private static final int FINISHGETDETAIL=1;//完成数据请求
	private ActivityDetailBean entity;//活动详情具体json内容
	private TextView interst,paticipate,uploadTxt,activityTitleTxt,activityTimeTxt,activityAddressTxt,
	activityHostTxt,activitytypeTxt,activityDescriptionTxt;
	private LinearLayout lin ;//布局中间图片
	/** 当前活动图片的位置 */
	private TextView pic_sum;
	private ImageView[] imageView ;
	private ImageView imagView;//作为中间转换
	private ImageView mainImgView;//活动主要图片
	private TextView topTitleTxt;//顶部标题
	private Button backBnt,shareBnt;
	private HashMap<String,String> map=new HashMap<String,String>();
	private static int i=0;
	private String activityId;//作为存储传递进来的活动Id
	private MyHandler handler;
	private MyThread thread;
	private Context context;
	private final static int SENDINTEREST=1;
	private final static int SENDJOIN=2;
	private final static int INTERESTJOIN=3;
	
	public static Integer DPITYPE=0;//屏幕密度类型
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    MobclickAgent.onError(this);//自动捕获异常退出（FC ）
		setContentView(R.layout.activity_detail);
		
		context=ActivityDetail.this;
		Intent intent=getIntent();
		activityId=intent.getStringExtra("activityId");
		map.put("userId", UserInfoUtil.getValue(context, "userId", ""));
		map.put("activityId", activityId);
	    BaseUtil.startService(Task.DETAIL_ACTIVITY,this, map);//传递请求内容
		
		pic_sum = (TextView) findViewById(R.id.pic_sum);
		/*清单TextView*/
		interst=(TextView)findViewById(R.id.interst_txt_id);
		paticipate=(TextView)findViewById(R.id.join_txt_id);
		activityTitleTxt=(TextView)findViewById(R.id.title);
		activityTimeTxt=(TextView)findViewById(R.id.time);
		activityAddressTxt=(TextView)findViewById(R.id.address);
		activityHostTxt=(TextView)findViewById(R.id.hold);
		activitytypeTxt=(TextView)findViewById(R.id.type);
		activityDescriptionTxt=(TextView)findViewById(R.id.h_com);
		uploadTxt=(TextView)findViewById(R.id.upload_txt_id);
		topTitleTxt=(TextView)findViewById(R.id.top_bar_title_txt_id);
		/*获取button id*/
		backBnt=(Button)findViewById(R.id.back_bnt);
		shareBnt=(Button)findViewById(R.id.top_right_Bnt_id);
		backBnt.setText("返回");
		shareBnt.setText("分享");
		//
		lin= (LinearLayout) findViewById(R.id.layout);
		mainImgView=(ImageView)findViewById(R.id.detail_main_pic_id);
		
		handler=new MyHandler();
	
		Log.i("ActivityDetail","ActivityDetail-->onCreate");
		
	}
	
	/** 图片按钮事件 **/
	private class PicActionListener implements OnClickListener {
		public void onClick(View v) {
			for (int i = 0; i < imageView.length; i++) {
				if (v == imageView[i]) {
					imageView[i].setBackgroundColor(Color.YELLOW);
					pic_sum.setText("(" + (i + 1) + "/" + imageView.length + ")");
				} else {
					imageView[i].setBackgroundColor(Color.WHITE);
				}
			}
			Intent intent = new Intent(ActivityDetail.this,
					ShowPicActivity.class);
			//传递大图片的地址集合
			
			List<String> bigurls=entity.getAllActivityBigUrl();
			ArrayList<String> list=new ArrayList<String>();
			for(String s:bigurls){
				list.add(s);
			}
			intent.putStringArrayListExtra("bigImgUrls", list);
			startActivity(intent);
		}
	}
    /*将获取到的结果动态布局*/
	public void layout(String detail){
		Log.i("ActivityDetail","ActivityDetail--->"+"layout");
		//将获取到的json转化为ActivityDetailEntity对象
		Type type=new TypeToken<ActivityDetailBean>(){}.getType();
		entity=(ActivityDetailBean)BaseUtil.getEntityFromJson(detail, type);
		
		/*获取对象ActivityDetailEntity的中属性值*/
		String activityTime=entity.getMainActivityTime();
		String activityType=entity.getMainActivitytype();
		String activityTitle=entity.getMainActivityTitle();
		String activityAddress=entity.getMainActivityAddress(); 
		String description=entity.getActivityDescription();
		String host=entity.getActivityHost();
		String mainImgUrl=entity.getDetailMainImgUrl();
		String isInterest=entity.getIsInterest();
		String isJoin=entity.getIsParticipate();
		String imgUrls="";
		int  position=0;
		
		List<String> actiUrlList=entity.getAllActivityUrl();
		
		/*判断是否感兴趣或参加*/
		if(isInterest.equals("1")){interst.setText("我感兴趣");interst.setTextColor(getResources().getColor(R.color.specgreen)); }
		if(isJoin.equals("1")){paticipate.setText("已参加");paticipate.setTextColor(getResources().getColor(R.color.specgreen));}
		activityTitleTxt.setText(activityTitle);
		activityTimeTxt .setText(activityTime);
		activityAddressTxt .setText(activityAddress);
		activityHostTxt.setText(host);
		activitytypeTxt.setText(activityType);
//		activityDescriptionTxt.setText(description);
		StringBuilder builder=new StringBuilder();
		
		description=description.replace("\\n", "\n").replace("\\t", "\t");
		 byte[] b=description.getBytes();
		 for(int i=0;i<b.length;i++){
			 Log.i("description","description:"+b[i]);
		 }
		 activityDescriptionTxt.setText(description);
//		hightLightTxt(builder.toString(),activityDescriptionTxt);
		//设置TextView可以点击
		activityDescriptionTxt.setMovementMethod(LinkMovementMethod.getInstance());
		
		topTitleTxt.setText(R.string.activity_detail_title);
		topTitleTxt.setTextColor(android.graphics.Color.WHITE);//设置标题
		
		imageView=new ImageView[actiUrlList.size()];//初始化ImageView数组大小
		AsyncDownload drawable=AsyncDownload.getInstance();
		/*实现ImageView异步加载布局 */
		for ( position = 0; position < actiUrlList.size(); position++) {
			imageView[position] = new ImageView(this);
			imageView[position].setScaleType(ImageView.ScaleType.FIT_XY);
			setImgLayoutParam(imageView[position]);
			imgUrls=BaseUtil.getPicUrl(context, actiUrlList.get(position));
			Log.i("AcDetail","imgUrls:"+imgUrls);
			Drawable draw=drawable.imageDown(imageView[position],imgUrls, new CallBack(){
				@Override
				public void imgDown(ImageView imagView,Drawable drawable) {
					imagView.setImageDrawable(drawable);
					
				}});
			if(draw!=null){//若缓存中仍然存在，则从获取的draw直接布局
				imageView[position].setImageDrawable(draw);
			}
			imageView[position].setOnClickListener(new PicActionListener());
			lin.addView(imageView[position]);
		}
		/*上部图片布局*/
		imgUrls=BaseUtil.getPicUrl(context,mainImgUrl);
//		imgUrls=HttpUtil.picUrl+"angel/"+mainImgUrl;
		
		Drawable draw=drawable.imageDown(mainImgView,imgUrls, new CallBack(){
			@Override
			public void imgDown(ImageView imagView,Drawable drawable) {
				imagView.setImageDrawable(drawable);
			}});
		if(draw!=null){//若缓存中仍然存在，则从获取的draw直接布局
			mainImgView.setImageDrawable(draw);
		}
		//
		if(actiUrlList.size()==0){
			pic_sum.setText("(0/0" + ")");
		}else{
		    pic_sum.setText("(1/" + actiUrlList.size() + ")");
		}
	}
	
	/**设置文本中URL为红色高亮
	 * @param str  文本
	 * @param tView 要设置高亮的TextView对象
	 */
	public void hightLightTxt(String str,TextView tView){
		String regExp="(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?";
		   Pattern pattern=Pattern.compile(regExp);
		   Matcher m=pattern.matcher(str);
		   SpannableStringBuilder  sp=new SpannableStringBuilder(str);//生成该对象
		   String urls="";
		   while(m.find()){
			  urls= m.group();
			  sp.setSpan(new ForegroundColorSpan(Color.GREEN),m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//			  sp.setSpan(new URLSpan(urls), m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		   }
		   
		   tView.setText(sp);
	}
	/**根据分辨率动态设置gallery的图片大小
	 * @param img ImgView对象
	 */
	public void setImgLayoutParam(ImageView img){
		int dpiType=BaseUtil.getDpiType(this);
		switch(dpiType){
		case 1:
			img.setLayoutParams(new Gallery.LayoutParams( 67,
					85));
			break;
		case 2:
			img.setLayoutParams(new Gallery.LayoutParams( 75,
					95));
			break;
		case 3:
			img.setLayoutParams(new Gallery.LayoutParams( 90,
					116));
			break;
		default:
				break;
		}
	}
	/**以下方法是按钮点击监听事件，分别为返回，分享，感兴趣，参见，上传图片
	 * @param v
	 */
	public void show_sharedialog(View v) {
		String topic=entity.getMainActivityTitle();//活动标题
		String activityTime=entity.getMainActivityTime();//活动时间
		List<String> activityNetAddress=StringUtil.checkURLList(entity.getActivityDescription());//活动描述中地址集合
		String netAddress="";
		
		String activityAddress=entity.getMainActivityAddress();
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
		if(activityNetAddress.size()>=1){
			netAddress=activityNetAddress.get(activityNetAddress.size()-1);//获取最后一个官网地址}
			intent.putExtra(Intent.EXTRA_TEXT,"早安天使:"+topic+"\r\n"+"时间:"+activityTime+"\r\n"+"地址:"+activityAddress+"\r\n"+"详情:"+netAddress);
		}
		else{
			intent.putExtra(Intent.EXTRA_TEXT,"早安天使:"+topic+"\r\n"+"时间:"+activityTime+"\r\n"+"地址:"+activityAddress+"\r\n");
		}
		startActivity(intent);
	}
	/*返回*/
	public void share_back(View v) {
			finish();
			TaskService.removeActivity(this);
	}
	/*点击表示对该活动感兴趣*/
	public void clickInterstBnt(View v){
		boolean b=BaseUtil.isBindPhone(context);
		if(b){
			if(!interst.getText().toString().equals("我感兴趣")){
				map.put("userId", UserInfoUtil.getValue(context, "userId", ""));
				map.put("activityId", activityId);
				map.put("isInterest", "1");
				if(paticipate.getText().toString().equals("已参加")){//发送当前状态
					map.put("isParticipate", "1");
				}else{
					map.put("isParticipate", "0");
				}
				new MyThread().start();
			}
		}else{
			Intent tent=new Intent(ActivityDetail.this,Register1Activity.class);
			tent.putExtra("isBind", "1");//表示手机号绑定
			startActivity(tent);
			TaskService.removeActivity(this);
		}
		
	}
	/*点击表示参加该活动*/
	public void clickJoinBnt(View v){
		boolean b=BaseUtil.isBindPhone(context);
		if(b){//若手机号已绑定
			if(!paticipate.getText().toString().equals("已参加")){
				map.put("userId", UserInfoUtil.getValue(context, "userId", ""));
				map.put("activityId", activityId);
				map.put("isParticipate", "1");
				if(interst.getText().toString().equals("我感兴趣")){//发送当前状态
					map.put("isInterest", "1");
				}else{
					map.put("isInterest", "0");
				}
				new MyThread().start();
			}
		}else{//跳转到注册页面
			Intent tent=new Intent(ActivityDetail.this,Register1Activity.class);
			tent.putExtra("isBind", "1");//表示手机号绑定
			startActivity(tent);
			TaskService.removeActivity(this);
		}
	}
	
	/** 选择图片上传
	 * @param v
	 */
	public void clickUploadpicBnt(View v){
		if(NetUtil.checkNetState(context)){//当网络连接正常
			boolean b=BaseUtil.isBindPhone(context);
			MobclickAgent.onEvent(this, "upLoadPic");//发送点击发送相片到友盟
			
			if(b){
				Intent intent=new Intent();
				intent.setAction(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				startActivityForResult(intent,1);
			}else{
				Intent tent=new Intent(ActivityDetail.this,Register1Activity.class);
				tent.putExtra("isBind", "1");//表示手机号绑定
				startActivity(tent);
			}
		}
	}
	class MyThread extends Thread{
		public void run(){
			String url=HttpUtil.baseUrl+"activityStatus";
			try {
				String result=HttpUtil.httpPost(url, map);
				Message msg=handler.obtainMessage();
				if(map.get("isInterest").equals("1")&&map.get("isParticipate").equals("0")){//判断是点击参加还是感兴趣
					msg.what=SENDINTEREST;
				}else if(map.get("isInterest").equals("0")&&map.get("isParticipate").equals("1")){
					msg.what=SENDJOIN;
				}else if(map.get("isInterest").equals("1")&&map.get("isParticipate").equals("1")){
					msg.what=INTERESTJOIN;
				}
				msg.obj=result;
				handler.sendMessage(msg);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}finally{
				map=new HashMap<String,String>();
			}
		}
	}
	class MyHandler extends Handler{
		public void handleMessage(Message msg){
				String isSuccess=BaseUtil.getValueFromJSON((String)msg.obj);
				
				 if(isSuccess.equals("2")){
					 BaseUtil.makeToast(context, "对不起,网络连接超时,请稍后重试...");
					 return ;
				}
				switch(msg.what){
				case SENDINTEREST:
					if(isSuccess.equals("1"))
						BaseUtil.makeToast(ActivityDetail.this, "感谢对该活动感兴趣");
						interst.setText("我感兴趣");
						interst.setTextColor(getResources().getColor(R.color.specgreen));
					break;
				case SENDJOIN:
					if(isSuccess.equals("1"))
						BaseUtil.makeToast(ActivityDetail.this, "成功参加活动");
						paticipate.setText("已参加");
						paticipate.setTextColor(getResources().getColor(R.color.specgreen));
					break;
				case INTERESTJOIN:
					BaseUtil.makeToast(ActivityDetail.this, "感谢您的参与");
					paticipate.setText("已参加");
					interst.setText("我感兴趣");
					paticipate.setTextColor(getResources().getColor(R.color.specgreen));
					interst.setTextColor(getResources().getColor(R.color.specgreen));
					break;
				}
		}
	}
	
	@Override
	public void init() {
		
	}
	@Override
	public void refresh(Object... params) {
		 String isSucess=BaseUtil.getValueFromJSON((String)params[0]);
		
		 if(isSucess.equals("2")){
			 BaseUtil.makeToast(ActivityDetail.this, "对不起,网络连接超时,请稍后重试...");
			 return ;
		}
		layout(params[0]+"");
	}

	@Override
	protected void onResume() {
		super.onResume();
		int i=0;
		MobclickAgent.onResume(this);
//		BaseUtil.startService(Task.DETAIL_ACTIVITY,this, map);//传递请求内容
		Log.i("ActivityDetail","ActivityDetail--->onResume start"+i++);
	}
	@Override
	protected void onDestroy() {
		TaskService.removeActivity(this);
		super.onDestroy();
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK){
			//为了保持跳转时该Activity仍保存在栈中
//			BaseUtil.showExitDialog(this);
			finish();
			TaskService.removeActivity(this);
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode==RESULT_OK){
			Uri uri=data.getData();
			String picUrl=BaseUtil.getUrlByUri(uri, ActivityDetail.this);
			//启动异步线程上传图片
		    
			new MyAsyncTask(context,uploadTxt).execute(picUrl);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	@Override
	protected void onPause() {
		super.onPause();
	    MobclickAgent.onPause(this);
	}
}

class MyAsyncTask extends AsyncTask<String,Integer,String>{
	private Context context;
	private TextView uploadTxt;
	private boolean isfinish=true;
	private MyHandler handler;
	private int count=0;
	public MyAsyncTask(Context context,TextView uploadTxt){
		this.context=context;
		this.uploadTxt=uploadTxt;
		handler=new MyHandler(uploadTxt);
	}
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		new Thread(){//用于动态
			public void run(){
				while(isfinish){
					Message msg=new Message();
					msg.what=count;
					handler.sendMessage(msg);
					try {
						Thread.sleep(400);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}
	
	class MyHandler extends Handler{
		private TextView uploadTxt;
		public MyHandler(TextView uploadTxt){
			this.uploadTxt=uploadTxt;
		}
		public void handleMessage(Message msg){
			switch(msg.what){
			case 0:
				this.uploadTxt.setText("上传中..");
				this.uploadTxt.setTextColor(context.getResources().getColor(R.color.red));
				count=1;
				break;
			case 1:
				this.uploadTxt.setText("上传中...");
				this.uploadTxt.setTextColor(context.getResources().getColor(R.color.red));
				count=0;
				break;
			}
		}
	}
	@Override
	protected String doInBackground(String... params) {
		String result=null;
		HashMap<String,String> map=new HashMap<String,String>();
		map.put("userId", UserInfoUtil.getValue(context, "userId", "1"));
		map.put("activityId", UserInfoUtil.getValue(context, "activityId", "1"));
		File file=new File(params[0]);//根据路径获取File
		map.put("filePath", file.getAbsolutePath());
		FormFile formFile=new FormFile(file.getName(),file,"image/gif","file");
		String url=HttpUtil.baseUrl+"upload";
		try {
			//执行上传图片，获取返回结果
			result=UpLoadPicUtil.post(url, map, formFile);
		} catch (IOException e) {
			e.printStackTrace();
			return "{'isSuccess':'2'}";
		}
		return result;
	}
	@Override
	protected void onPostExecute(String result) {
		String isSuccess=BaseUtil.getValueFromJSON(result);
		
		 if(isSuccess.equals("2")){
			 BaseUtil.makeToast(context, "对不起,网络连接超时,请稍后重试...");
			 return ;
		}
			if(isSuccess.equals("1")){
				isfinish=false;//停止线程
				BaseUtil.makeToast(this.context,"上传完成,感谢您的分享");
				this.uploadTxt.setText("上传图片");
				this.uploadTxt.setTextColor(context.getResources().getColor(R.color.white));
			}
	}
	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
	}
	@Override
	protected void onCancelled() {
		super.onCancelled();
	}
}

class DescribeTxt{
	private String content;
	public DescribeTxt(String content){
		this.content=content;
	}
	public void setContent( String content){
		this.content=content;
	}
	public String getContent(){
		return content;
	}
}